package file

import (
	"fmt"
	"github.com/disintegration/imaging"
	"github.com/gin-gonic/gin"
	"io/ioutil"
	"mime/multipart"
	"os"
	"path/filepath"
	"strings"
	"wskyygyso/api/pkg/app"
	"wskyygyso/api/pkg/auth"
	"wskyygyso/api/pkg/helpers"
)

//Put 写入文件
func Put(body []byte, to string) error {
	err := ioutil.WriteFile(to, body, 0644)
	if err != nil {
		return err
	}
	return nil
}

//Exists 文件是否存在
func Exists(file string) bool {
	if _, err := os.Stat(file); os.IsNotExist(err) {
		return false
	}
	return true
}

//FileNameWithoutExtension 获取文件名 剔除后缀
func FileNameWithoutExtension(fileName string) string {
	return strings.TrimSuffix(fileName, filepath.Ext(fileName))
}

//SaveUploadAvatar 上传头像
func SaveUploadAvatar(c *gin.Context, header *multipart.FileHeader) (string, error) {
	var avatar string
	publicPath := "public"
	dirName := fmt.Sprintf("/uploads/avatar/%s/%s/", app.TimenowInTimezone().Format("2006/01/02"), auth.CurrentUID(c))
	os.MkdirAll(publicPath+dirName, 0755)
	fileName := randomNameFromUploadFile(header)
	avatarPath := publicPath + dirName + fileName
	if err := c.SaveUploadedFile(header, avatarPath); err != nil {
		return avatar, err
	}
	//裁剪图片
	img, err := imaging.Open(avatarPath, imaging.AutoOrientation(true))
	if err != nil {
		return avatar, nil
	}
	resizeAvatar := imaging.Thumbnail(img, 256, 256, imaging.Lanczos)
	resizeAvatarName := randomNameFromUploadFile(header)
	resizeAvatarPath := publicPath + dirName + resizeAvatarName
	err = imaging.Save(resizeAvatar, resizeAvatarPath)
	if err != nil {
		return avatar, err
	}
	err = os.Remove(avatarPath)
	if err != nil {
		return avatar, err
	}
	return resizeAvatarPath, nil
}

func randomNameFromUploadFile(file *multipart.FileHeader) string {
	return helpers.RandomNumber(16) + filepath.Ext(file.Filename)
}
